package com.gl.Filter;

import com.gl.pojo.entity.User;
import com.gl.service.UserService;
import com.gl.utils.CurrentHolder;
import com.gl.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@WebFilter(urlPatterns = "/*", asyncSupported = true)
@Component
public class TokenFilter implements Filter {

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        String method = request.getMethod();

        // 放行预检
        if ("OPTIONS".equalsIgnoreCase(method)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 无须校验
        if (requestURI.contains("/register") || requestURI.contains("/captcha") || requestURI.contains("/login") || requestURI.contains("/ai")) {
            filterChain.doFilter(request, response);
            return;
        }
        //无令牌
        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            //校验成功
            Claims claims = JwtUtils.parseToken(token);
            String uid = claims.get("uid").toString();
            CurrentHolder.setCurrentId(uid); //存入

            //uri里面包含admin，判断是否是管理员
            if (requestURI.contains("/admin") || requestURI.contains("/system")) {
                User user = userService.selectById(uid);
                if (user.getRole().equals("1")) {
                    filterChain.doFilter(request, response);
                    return;
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } catch (Exception e) {
            //校验失败
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //放行
        try {
            filterChain.doFilter(request, response);
        } finally {
            CurrentHolder.removeCurrentId();
        }
    }
}
